package com.longma.server.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.longma.server.dao.DailyDataDAO;
import com.longma.server.entity.DailyData;
import com.longma.server.service.IDailyDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

/**
 * 日发电量服务类
 */
@Service
public class DailyDataServiceImpl implements IDailyDataService {

    @Autowired
    private DailyDataDAO dailyDataDAO;

    /**
     * 插入日发发电量、用电量数据
     */
    @Override
    public DailyData addDailyData(DailyData dailyData) {
        // 查找数据是否存在
        if(dailyDataDAO.count(Wrappers.<DailyData>lambdaQuery().eq(DailyData::getDate,dailyData.getDate())
        .eq(DailyData::getYuncangId,dailyData.getYuncangId())) > 0){
            // 更新
            dailyDataDAO.update(Wrappers.<DailyData>lambdaUpdate().eq(DailyData::getDate,dailyData.getDate())
                    .eq(DailyData::getYuncangId,dailyData.getYuncangId())
                    .set(DailyData::getConsumption,dailyData.getConsumption())
            .set(DailyData::getGeneration,dailyData.getGeneration()));
        }else {
            // 不存在则新增
            dailyDataDAO.save(dailyData);
        }
        return dailyData;
    }

    /*
     * 根据云仓id获取当日发电量、用电量
     */
    @Override
    public DailyData getDailyData(Integer yuncangId) {
        LocalDate dNow = LocalDate.now();
        String curDate = dNow.toString();

        DailyData dailyData = dailyDataDAO.getOne(Wrappers.<DailyData>lambdaQuery().eq(DailyData::getYuncangId,yuncangId)
                .eq(DailyData::getDate, curDate));

        if(dailyData == null){
            dailyData = new DailyData();
            dailyData.setYuncangId(yuncangId);
            dailyData.setConsumption(0.0);
            dailyData.setGeneration(0.0);
            dailyData.setDate(dNow);
        }
        return dailyData;
    }
}
